/*
 * @lc app=leetcode.cn id=859 lang=javascript
 *
 * [859] 亲密字符串
 */

// @lc code=start
/**
 * @param {string} a
 * @param {string} b
 * @return {boolean}
 */
var buddyStrings = function (a, b) {
  if (a.length !== b.length) return false;
  // 字符相等，需要判断是否有重复字符
  if (a === b) return a !== [...new Set(a)].join('');

  let strA = '';
  let strB = '';
  let i = 0;
  while (i < a.length) {
    if (strA.length > 2 || strB.length > 2) return false;
    // 如果不相等，交换a中字符的位置
    if (a[i] !== b[i]) {
      strA = a[i] + strA;
      strB += b[i];
    }
    i++;
  }

  return strA === strB;
};
// @lc code=end
